from re import match, M
from apps.models.user import User
from apps.models.book import Book, Chapter
from ext.encrypt import hash_md5


# email验证
def re_email(arg):
    if match(r'^\w+([-+\.]\w+)*@\w+([-\.]\w+)*\.\w+$', arg):
        return True
    return False


# 密码验证
# 6-20位，至少包含字母与数字
def re_password(arg):
    if match(r'^\S{6,20}$', arg) and match(
            r'^.*\d.*[a-zA-Z].*$|^.*[a-zA-Z].*\d.*$', arg):
        return True
    return False


# 用户名验证
# 3-20位字符，不能包含空格
def re_user_name(arg):
    if match(r'^\S{3,20}$', arg):
        return True
    return False


# 数据合规性教研
# 检查用户数据
class CheckUserArgs:

    def __init__(
        self,
        email=None,
        password=None,
        repassword=None,
        new_password=None,
        user_name=None,
        captcha=None,
        user_id=None,
        login_user=False,
        email_used=False,
        email_not_used=False,
        user_name_not_used=False,
        password_right=False,
        return_user=False,
    ):

        self.email = email
        self.password = password
        self.repassword = repassword
        self.new_password = new_password
        self.user_name = user_name
        self.captcha = captcha
        self.user_id = user_id
        self.login_user = login_user
        self.email_used = email_used
        self.email_not_used = email_not_used
        self.user_name_not_used = user_name_not_used
        self.password_right = password_right
        self.return_user = return_user

    def checkEmail(self):
        if not re_email(self.email):
            return {"email": "邮箱地址格式错误，请重新填写"}
        return {}

    def checkPassword(self,name, value):
        if not re_password(value):
            return {name: "密码长度应为6-20位，至少包含一个数字和字母"}
        return {}

    def checkRepassword(self,repassword, password):
        if repassword != password:
            return {"repassword": "两次密码输入不一致，请重新输入"}
        return {}

    def checkUserName(self):
        if not re_user_name(self.user_name):
            return {"user_name": "昵称长度应为2-10位，只能包含字母、数字、下划线"}
        return {}

    def checkCaptcha(self):
        if self.captcha != '123456':
            return {"captcha": "验证码错误，请重新输入"}
        return {}

    def baseCheck(self):
        arg_dict = {
            'email': self.email,
            'password': self.password,
            'repassword': self.repassword,
            'new_password': self.new_password,
            'user_name': self.user_name,
            'captcha': self.captcha,
        }
        result = {}

        for k, v in arg_dict.items():
            if v == None:
                continue

            match k:
                case 'email':
                    result = self.checkEmail()
                case 'password':
                    result = self.checkPassword('password', v)
                case 'new_password':
                    result = self.checkPassword('new_password', v)
                case 'repassword':
                    result = self.checkRepassword(
                        self.repassword, self.password
                    ) if self.new_password == None else self.checkRepassword(
                        self.repassword, self.new_password)
                case 'user_name':
                    result = self.checkUserName()
                case 'captcha':
                    result = self.checkCaptcha()
                case _:
                    pass

            if result != {}:
                return result

        return result

    def checkEmailUsed(self):
        user = User.query.filter(User.email == self.email).filter(
            User.is_del == False).first()
        if not user:
            return {"email": "该邮箱未注册，请先注册"}
        return {}

    def checkLoginUser(self):
        user = User.query.filter(User.email == self.email).filter(
            User.is_del == False).filter(
                User.password == hash_md5(self.password)).first()
        if not user:
            return {"email": "邮箱或密码错误"}
        if self.return_user == True:
            return user
        return {}

    def checkUserNameNotUsed(self):
        user = User.query.filter(User.user_name == self.user_name).filter(
            User.is_del == False).first()
        if user:
            return {"user_name": "该昵称已注册，请重新输入"}
        return {}

    def checkEmailNotUsed(self):
        if User.query.filter(User.email == self.email).filter(
                User.is_del == False).first():
            return {"email": "该邮箱已注册，请直接登录"}
        return {}

    def checkPasswordRight(self):
        user = user.query.get(self.user_id)
        if user.password != hash_md5(self.password):
            return {"password": "密码错误"}
        return {}

    def queryCheck(self):
        arg_dict = {
            'login_user': self.login_user,
            'email_used': self.email_used,
            'email_not_used': self.email_not_used,
            'user_name_not_used': self.user_name_not_used,
            'password_right': self.password_right,
        }

        result = {}

        for k, v in arg_dict.items():
            if not v:
                continue
            match k:
                case 'login_user':
                    result = self.checkLoginUser()
                case 'email_used':
                    result = self.checkEmailUsed()
                case 'email_not_used':
                    result = self.checkEmailNotUsed()
                case 'user_name_not_used':
                    result = self.checkUserNameNotUsed()
                case 'password_right':
                    result = self.checkPasswordRight()
                case _:
                    pass
            if result != {}:
                return result

        return result

    def run(self):
        base_check_result = self.baseCheck()
        result = base_check_result if base_check_result != {} else self.queryCheck(
        )
        return result
    
    
    
# 检查书本数据
class CheckBookArgs:
    def __init__(
        self,
        book_id=None,
        return_book=False,
        
        chapter_id=None,
        return_chapter=False,
    ):
        self.book_id = book_id
        self.return_book = return_book
        
        self.chapter_id = chapter_id
        self.return_chapter = return_chapter
        
    def checkBookId(self):
        book = Book.query.get(self.book_id)
        if book is None or book.is_del == True:
            return {"book_id": "该书本不存在"}
        if self.return_book == True:
            return book
        return {}
    
    def checkChapterId(self):
        chapter = Chapter.query.get(self.chapter_id)
        if chapter is None or chapter.is_del == True:
            return {"chapter_id": "该章节不存在"}
        if self.return_chapter == True:
            return chapter
        return {}
    
    def run(self):
        if self.book_id != None:
            return  self.checkBookId()
        if self.chapter_id != None:
            return self.checkChapterId()
    